import { BaseSideService } from "@zeppos/zml/base-side";

function fileNameStamp() {
  const d = new Date();
  return d.getTime();
}

async function fetchData(res, params) {
  try {
    // Requesting network data using the fetch API
    // The sample program is for simulation only and does not request real network data, so it is commented here
    // Example of a GET method request
    // const { body: { data = {} } = {} } = await fetch({
    //   url: 'https://xxx.com/api/xxx',
    //   method: 'GET'
    // })
    // Example of a POST method request
    // const { body: { data = {} } = {} } = await fetch({
    //   url: 'https://xxx.com/api/xxx',
    //   method: 'POST',
    //   headers: {
    //     'Content-Type': 'application/json'
    //   },
    //   body: JSON.stringify({
    //     text: 'Hello Zepp OS'
    //   })
    // })
    // const fd = new FormData()
    // fd.append('file', params.audio)
    // fd.append('messages', params.messages)
    // fd.append('age', '18')
    // A network request is simulated here, Reference documentation: https://jsonplaceholder.typicode.com/
    const response = await fetch({
      url: 'https://ai.zscampus.com/psy/api/simChat',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: { messages: params.messages.messages,audioHex:params.audioHex }
    })
    const resBody = typeof response.body === 'string' ? JSON.parse(response.body) : response.body

    res(null, {
      result: resBody,
    });
  } catch (error) {
    res(null, {
      code: 0, data: "ERROR",
    });
  }
};


async function DownloadFile(res) {
  try {
    let fileName = fileNameStamp()
    this.call({
      message: `开始下载${fileName}`,
    });
    logger.log("========下载=========") // data://download/1.png
    const downloadTask = network.downloader.downloadFile({
      url: 'https://ai.zscampus.com/aistatic/voice/test.mp3',
      headers: {},
      timeout: 60000,
      filePath: `data://voice/${fileName}.mp3`
    })
    if (!downloadTask) {
      this.call({
        message: "download fail",
      });
      return;
    }


    downloadTask.onSuccess = (data) => {
      console.log("========下载完成=========") // data://download/1.png
      console.log(data.filePath) // data://download/1.png
      console.log(data.tempFilePath) // undefined
      console.log(data.statusCode) // 200
      this.call({
        result: { filePath: data.filePath }
      })

      downloadTask.onComplete = () => {
        console.log("download complete");
      };

      downloadTask.onProgress = (data) => {
        console.log("download progress", data);
      };
      downloadTask.onFail = (data) => {
        console.log("download fail", data);
        this.call({
          result: {
            data: "download fail",
          },
        });
      };
      // player.setSource(player.source.FILE, { file: 'data://voice/test.mp3' })
      // player.prepare()
    }


  } catch (error) {
    this.call({
      message: `下载出错了ERROR`, error,
    });
    res(null, {
      code: 0, data: "ERROR",
    });
  }
};

AppSideService(
  BaseSideService({
    onInit() { },

    onRequest(req, res) {
      console.log("===进入半生==>,");
      console.log("=====>,", req.method);

      if (req.method === "DOWNLOAD_FILE") {
        console.log("========调用了伴生下载=========") // data://download/1.png
        DownloadFile(res);
      }
      if (req.method === "GET_DATA") {
        fetchData(res, req.params);
      }
    },

    onRun() { },

    onDestroy() { },
  })
);
